using System;
using Bases;
using Configs;
using Modules.Game.Roles;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Modules.Game.Skills
{
    public class SkillItem : MonoBehaviourSimplify, IPointerMoveHandler, IPointerExitHandler
    {
        public Image iconImg;
        public TextMeshProUGUI orderText;

        public GameObject cdObj;
        public TextMeshProUGUI cdText;

        private readonly string[] _keyboardNames = {"Q", "W", "E", "R"};

        private int _order;

        private void Awake()
        {
            RegisterMsg(EventConfig.HeroReleaseSkill, OnHeroReleaseSkill);
        }

        private void Update()
        {
            var cd = HeroModel.Instance.GetSkillData(_order).Cd;

            if (cd <= 0) cdObj.SetActive(false);

            if (cdObj.activeSelf) cdText.text = Math.Round(cd, 1) + "";
        }

        public void OnPointerExit(PointerEventData eventData)
        {
            Delay(Time.deltaTime, () => { SendMsg(EventConfig.OpenSkillDescTip, null); });
        }

        public void OnPointerMove(PointerEventData eventData)
        {
            SendMsg(EventConfig.OpenSkillDescTip, new SkillDescData
            {
                Pos = GetComponent<RectTransform>().position,
                Order = _order
            });
        }

        protected override void OnBeforeDestroy()
        {
        }

        public void InitData(int order, SkillData configData)
        {
            _order = order;

            iconImg.sprite = Sprite.Create(Resources.Load<Texture2D>(configData.Img), new Rect(0, 0, 256, 256),
                new Vector2(0.5f, 0.5f));

            orderText.text = _keyboardNames[order];
        }

        private void OnHeroReleaseSkill(object order)
        {
            if ((int) order != _order) return;

            cdObj.SetActive(true);
        }
    }
}